package com.imy.common.view.recyclerview.adpater;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.imy.common.R;
import com.imy.common.util.DensityUtils;
import com.imy.common.view.recyclerview.MoreViewHolder;

import java.util.List;

/**
 * 功能描述：多布局（底部有加载更多视图）
 *
 * @author 黄一凡
 * @date 2018/8/13 0013
 */

public class BaseLoadMoreAdapter<T> extends BaseMultipleAdapter<T> {
  public static final int ITEM_TYPE_LOAD_MORE_VIEW = Integer.MAX_VALUE - 1;//加载更多
  public static final int ITEM_TYPE_NO_MORE_VIEW = Integer.MAX_VALUE - 2;//暂无更多
  public static final int ITEM_TYPE_LOAD_ERROR_VIEW = Integer.MAX_VALUE - 3;//加载出错
  public static final int ITEM_TYPE_HIDE_VIEW = Integer.MAX_VALUE - 4;//无视图，隐藏
  public static final int ITEM_TYPE_GET_MORE_VIEW = Integer.MAX_VALUE - 5;//上滑加载更多
  private Context mContext;
  private View mLoadMoreView;//加载更多视图
  private View mLoadErrorView;//加载出错视图
  private View mNoMoreView;//暂无更多视图
  private View mMoreView;//暂无更多视图
  private int mCurrentItemType = ITEM_TYPE_LOAD_MORE_VIEW;//默认是加载更多

  private boolean isHaveStatesView = true;//底部是否有状态视图
  private CallBack mCallBack;//目前只用于加载出错
  private final int STATUS_VIEW_HEIGHT;//状态视图的默认高度
  private final int TEXTVIEW_COLOR;//状态视图文本的默认文字颜色
  private final int TEXTVIEW_SIZE;//状态视图文本的默认文字大小

  private String mNoMoreText;//暂无更多视图的文案

  public BaseLoadMoreAdapter(Activity activity, List<T> items) {
    super(activity, items);
    this.mContext = activity;
    STATUS_VIEW_HEIGHT = DensityUtils.dp2px(activity, 52);
    TEXTVIEW_COLOR = Color.parseColor("#999999");
    TEXTVIEW_SIZE = 12;
  }

  /**
   * 展示加载更多
   */
  public void showLoadMore() {
    mCurrentItemType = ITEM_TYPE_LOAD_MORE_VIEW;
    isHaveStatesView = true;
    notifyItemChanged(getItemCount());
  }

  /**
   * 展示上滑加载更多
   */
  public void showMore() {
    mCurrentItemType = ITEM_TYPE_GET_MORE_VIEW;
    isHaveStatesView = true;
    notifyItemChanged(getItemCount());
  }

  /**
   * 展示加载出错
   */
  public void showLoadError(CallBack callBack) {
    this.mCallBack = callBack;
    mCurrentItemType = ITEM_TYPE_LOAD_ERROR_VIEW;
    isHaveStatesView = true;
    notifyItemChanged(getItemCount());
  }

  /**
   * 展示暂无更多内容
   */
  public void showNoMore(String text) {
    if (!TextUtils.isEmpty(text)) {
      mNoMoreText = text;
    } else {
      mNoMoreText = mContext.getString(R.string.footer_no_more);
    }
    mCurrentItemType = ITEM_TYPE_NO_MORE_VIEW;
    isHaveStatesView = true;
    if (mNoMoreView instanceof TextView) {
      ((TextView) mNoMoreView).setText(mNoMoreText);
    }
    notifyItemChanged(getItemCount());
  }

  /**
   * 展示暂无更多内容
   */
  public void showNoMore() {
    showNoMore(null);
  }

  /**
   * 隐藏底部视图
   */
  public void hideLoadMore() {
    mCurrentItemType = ITEM_TYPE_HIDE_VIEW;
    isHaveStatesView = false;
    notifyDataSetChanged();
  }

  @Override
  public int getItemViewType(int position) {
    if (isHaveStatesView && isFooterItem(position)) {
      return mCurrentItemType;
    }
    return super.getItemViewType(position);
  }

  @Override
  public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    if (viewType == ITEM_TYPE_LOAD_MORE_VIEW) {
      return getLoadMoreViewHolder();
    } else if (viewType == ITEM_TYPE_LOAD_ERROR_VIEW) {
      RecyclerView.ViewHolder viewHolder = getLoadErrorViewHolder();
      viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          if (mCallBack != null) {
            mCallBack.onErrorViewClick(v);
          }
        }
      });
      return viewHolder;
    } else if (viewType == ITEM_TYPE_GET_MORE_VIEW) {
      return getMoreViewHolder();
    } else if (viewType == ITEM_TYPE_NO_MORE_VIEW) {
      return getNoMoreViewHolder();
    }
    return super.onCreateViewHolder(parent, viewType);
  }

  @Override
  public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    if (!isFooterType(holder.getItemViewType())) {
      super.onBindViewHolder(holder, position);
    }
  }

  @Override
  public void onAttachedToRecyclerView(RecyclerView recyclerView) {
    super.onAttachedToRecyclerView(recyclerView);
    final RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
    if (layoutManager instanceof GridLayoutManager) {
      final GridLayoutManager gridLayoutManager = (GridLayoutManager) layoutManager;
      final GridLayoutManager.SpanSizeLookup spanSizeLookup = gridLayoutManager.getSpanSizeLookup();

      gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
          if (isHaveStatesView && (position == getItemCount() - 1)) {
            return ((GridLayoutManager) layoutManager).getSpanCount();
          }
          if (isHaveStatesView && (spanSizeLookup != null)) {
            return spanSizeLookup.getSpanSize(position);
          }
          return 1;
        }
      });
      gridLayoutManager.setSpanCount(gridLayoutManager.getSpanCount());
    }
  }

  @Override
  public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
    if (holder instanceof MoreViewHolder) {
      if (isHaveStatesView && (holder.getLayoutPosition() == getItemCount() - 1)) {
        ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();

        if (lp != null
            && lp instanceof StaggeredGridLayoutManager.LayoutParams) {
          StaggeredGridLayoutManager.LayoutParams p = (StaggeredGridLayoutManager.LayoutParams) lp;

          p.setFullSpan(true);
        }
      }
    } else {
      super.onViewAttachedToWindow(holder);
    }
  }

  @Override
  public void onViewDetachedFromWindow(RecyclerView.ViewHolder holder) {
    if (holder instanceof MoreViewHolder) {
    } else {
      super.onViewDetachedFromWindow(holder);
    }
  }

  @Override
  public void onViewRecycled(RecyclerView.ViewHolder holder) {
    if (holder instanceof MoreViewHolder) {
    } else {
      super.onViewRecycled(holder);
    }
  }

  /**
   * 获取加载更多视图
   *
   * @return 更多视图View的持有者
   */
  private MoreViewHolder getLoadMoreViewHolder() {
    if (mLoadMoreView == null) {
      LinearLayout linearLayout = new LinearLayout(mContext);
      linearLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
          STATUS_VIEW_HEIGHT));
      linearLayout.setOrientation(LinearLayout.HORIZONTAL);
      linearLayout.setGravity(Gravity.CENTER);
      //添加ProgressBar
      ProgressBar pb = new ProgressBar(mContext);
      LinearLayout.LayoutParams pbLL = new LinearLayout.LayoutParams(
          DensityUtils.dp2px(mContext, 20), DensityUtils.dp2px(mContext, 20));
      pb.setLayoutParams(pbLL);
      Drawable indeterminateDrawable = mContext.getResources().getDrawable(
          R.drawable.more_loading);
      pb.setIndeterminateDrawable(indeterminateDrawable);
      linearLayout.addView(pb);
      //添加TextView
      TextView tv = new TextView(mContext);
      LinearLayout.LayoutParams tvLL = new LinearLayout.LayoutParams(
          LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
      tvLL.setMargins(DensityUtils.dp2px(mContext, 16), 0, 0, 0);
      tv.setLayoutParams(tvLL);
      tv.setIncludeFontPadding(false);
      tv.setTextColor(TEXTVIEW_COLOR);
      tv.setTextSize(TEXTVIEW_SIZE);
      tv.setText(mContext.getString(R.string.footer_load_more));
      linearLayout.addView(tv);
      mLoadMoreView = linearLayout;
    }
    return MoreViewHolder.createViewHolder(mContext, mLoadMoreView);
  }

  /**
   * 获取加载出错视图
   *
   * @return 更多视图View的持有者
   */
  private MoreViewHolder getLoadErrorViewHolder() {
    if (mLoadErrorView == null) {
      TextView tv = new TextView(mContext);
      tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
          STATUS_VIEW_HEIGHT));
      tv.setTextColor(TEXTVIEW_COLOR);
      tv.setTextSize(TEXTVIEW_SIZE);
      tv.setGravity(Gravity.CENTER);
      tv.setText(mContext.getString(R.string.footer_load_error));
      mLoadErrorView = tv;
    }
    return MoreViewHolder.createViewHolder(mContext, mLoadErrorView);
  }

  /**
   * 获取加载更多视图
   *
   * @return 更多视图View的持有者
   */
  private MoreViewHolder getNoMoreViewHolder() {
    if (mNoMoreView == null) {
      TextView tv = new TextView(mContext);
      tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
          STATUS_VIEW_HEIGHT));
      tv.setGravity(Gravity.CENTER);
      tv.setTextColor(TEXTVIEW_COLOR);
      tv.setTextSize(TEXTVIEW_SIZE);
      tv.setText(mNoMoreText);

      mNoMoreView = tv;
    }
    return MoreViewHolder.createViewHolder(mContext, mNoMoreView);

  }

  /**
   * 上滑加载更多
   *
   * @return 更多视图View的持有者
   */
  private MoreViewHolder getMoreViewHolder() {
    if (mMoreView == null) {
      TextView tv = new TextView(mContext);
      tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
          STATUS_VIEW_HEIGHT));
      tv.setGravity(Gravity.CENTER);
      tv.setTextColor(TEXTVIEW_COLOR);
      tv.setTextSize(TEXTVIEW_SIZE);
      tv.setText("上滑加载更多");

      mMoreView = tv;
    }
    return MoreViewHolder.createViewHolder(mContext, mMoreView);

  }

  @Override
  public int getItemCount() {
    return super.getItemCount() + (isHaveStatesView ? 1 : 0);
  }

  private boolean isFooterType(int type) {
    return type == ITEM_TYPE_LOAD_MORE_VIEW ||
        type == ITEM_TYPE_LOAD_ERROR_VIEW ||
        type == ITEM_TYPE_NO_MORE_VIEW ||
        type == ITEM_TYPE_HIDE_VIEW ||
        type == ITEM_TYPE_GET_MORE_VIEW;
  }

  /**
   * 设置底部是否有状态视图
   *
   * @param haveStatesView 是否有状态视图
   */
  public void setHaveStatesView(boolean haveStatesView) {
    isHaveStatesView = haveStatesView;
  }

  public boolean isHaveStatesView() {
    return isHaveStatesView;
  }

  private boolean isFooterItem(int position) {
    return position == getItemCount() - 1;
  }

  public interface CallBack {
    void onErrorViewClick(View view);
  }
}
